package cn.itrip.auth.service;


import cn.itrip.auth.exception.TokenDateException;
import cn.itrip.beans.pojo.ItripUser;
import cn.itrip.beans.vo.ItripTokenVO;
import cn.itrip.common.*;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

/**
 * @author Tequila
 **/
@Service
@Slf4j
public class TokenServiceImpl implements TokenService {

    @Autowired
    private RedisUtils redisUtils;

    @Override
    public String getToken(String userAgent, ItripUser itripUser) {

        //key: token:PC-USERCODE[加密]-USERID-CREATIONDATE-RONDEM[6 位]
        StringBuilder sb = new StringBuilder();

        if(UserAgentUtil.CheckAgent(userAgent)){
            // 移动端
            sb.append("token:MOBILE-");
        }else{
            //PC端
            sb.append("token:PC-");
        }
        // 拼接
        sb.append(MD5.getMd5(itripUser.getUsercode(),32));
        sb.append("-");
        sb.append(itripUser.getId());
        sb.append("-");
        // 当前时间
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        String createDate = sdf.format(new Date());
        sb.append(createDate);
        sb.append("-");
        String code = RandomStringUtils.randomNumeric(6);
        sb.append(code);
        //value: 用户对象json
        log.info(sb.toString());
        return sb.toString();
    }

    public ItripTokenVO getToken1(String userAgent, ItripUser itripUser) throws ParseException {

        //key: token:PC-USERCODE[加密]-USERID-CREATIONDATE-RONDEM[6 位]
        StringBuilder sb = new StringBuilder();

        if(UserAgentUtil.CheckAgent(userAgent)){
            // 移动端
            sb.append("token:MOBILE-");
        }else{
            //PC端
            sb.append("token:PC-");
        }
        // 拼接
        sb.append(MD5.getMd5(itripUser.getUsercode(),32));
        sb.append("-");
        sb.append(itripUser.getId());
        sb.append("-");
        // 当前时间
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        String createDate = sdf.format(new Date());
        sb.append(createDate);
        sb.append("-");
        String code = RandomStringUtils.randomNumeric(6);
        sb.append(code);
        //value: 用户对象json
        log.info(sb.toString());
        String token = sb.toString();
        // 封装到vo 中
        // 返回vo  itripTokenVo
        ItripTokenVO tokenVO = new ItripTokenVO();
        tokenVO.setToken(token);
        // key: token:PC-USERCODE[加密]-USERID-CREATIONDATE-RONDEM[6 位]
        String createTokenDate = token.split("-")[3];
        Date genDate = new SimpleDateFormat("yyyyMMddHHmmss").parse(createTokenDate);
        long time = genDate.getTime();
        tokenVO.setGenTime(time);
        // 两个小时  ==
        tokenVO.setExpTime(time+(60*60*2*1000));
        return tokenVO;
    }

    @Override
    public ItripTokenVO reToken(String token, String userAgent) throws ParseException, TokenDateException, JsonProcessingException {

        // 1.过期时间还剩半个小时之内才运行置换
        String dateStr = token.split("-")[3];
        Date date = DateUtil.parse(dateStr, "yyyyMMddHHmmss");
        // 拿着当前系统时间 - token时间 大于半个小时  不允许置换
        //Calendar.getInstance().getTimeInMillis() // 当前系统时间戳
        //System.currentTimeMillis()
        if(Calendar.getInstance().getTimeInMillis() - date.getTime() < 60*90*1000){

            // 12:20   12:30   2小时 -   10
           throw  new TokenDateException("token时间还没有过期不允许置换");
        }
        // 从redis中拿对象信息
        String itripUserStr = (String) redisUtils.get(token);
        ObjectMapper objectMapper = new ObjectMapper();
        ItripUser itripUser = objectMapper.readValue(itripUserStr, ItripUser.class);
        // 2. 生成新的token
        ItripTokenVO itripTokenVO = getToken1(userAgent, itripUser);

        // 3. 存入redis中
        redisUtils.set(itripTokenVO.getToken(),itripUser,60*60*2);

        // 4.老token续命2分钟
        redisUtils.set(token,itripUser,2*60);
        return itripTokenVO;
    }
}
